package cn.andrewlu.weexshell.weex.core;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.FrameLayout;

import com.taobao.weex.utils.WXFileUtils;

import cn.andrewlu.weexshell.beans.WXAppModel;
import cn.andrewlu.weexshell.beans.WXPage;
import cn.andrewlu.weexshell.ui.NavFragment;

/**
 * Created by andrewlu on 2017/6/6.
 */

public class WXAppManager {
    private Context mContext;
    private WXAppModel mAppModel;

    private static class Holder {
        private static WXAppManager sInstance = new WXAppManager();
    }

    private WXAppManager() {
    }

    public static WXAppManager getInstance() {
        return Holder.sInstance;
    }

    public void initApp(Context context, String appRootPath) {
        this.mContext = context;
        mAppModel = WXAppParser.parse(WXFileUtils.loadFileOrAsset(appRootPath, context));
    }

    public WXAppModel getAppModel() {
        return mAppModel;
    }

    public WXPage getPage(String pageName) {
        if (mAppModel != null && mAppModel.getPages() != null) {
            return mAppModel.getPages().get(pageName);
        }
        return null;
    }

    public void launch(AppCompatActivity context) {
        if (this.mContext == null) {
            initApp(context, "app.conf.json");
        }
        WXAppModel model = getAppModel();
        if (model == null) return;
        NavFragment root = NavPageFactory.instanceOfNav(model.getNavType());
        if (root != null) {
            root.setNavData(model.getNav());

            View view = new FrameLayout(context);
            view.setId(android.R.id.content);
            context.setContentView(view);
            context.getSupportFragmentManager().beginTransaction()
                    .add(android.R.id.content, root, "RootView")
                    .commit();
        }
    }
}
